""" 遍历当前目录和子目录下的头文件，把它们的编码改为gb2312编码 """
import os
import re
import codecs
import chardet

def get_all_files(path):
    """ 获取所有头文件 """
    all_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.h'):
                all_files.append(os.path.join(root, file))
    return all_files

if __name__ == "__main__":
    all_files = get_all_files('.')

    # 遍历所有文件
    for file in all_files:
        # 获取文件名
        file_name = os.path.splitext(file)[0]
        # 获取文件后缀
        file_ext = os.path.splitext(file)[1]
        # 判断是否是头文件
        if file_ext == ".h":
            # 读取头文件内容
            with open(file, "rb") as f:
                content = f.read()
                # 判断文件编码
                if chardet.detect(content)['encoding'] != 'GB2312':
                    # 读取头文件内容
                    with codecs.open(file, "r", encoding='utf-8') as f:
                        content = f.read()
                        # 重新写入头文件
                        with codecs.open(file, "w", encoding='gb2312') as f:
                            f.write(content)